package com.defangit.applicant.orm;

import com.defangit.applicant.domain.Ticket;
import com.defangit.award.orm.HibernateUtil;
import common.Assert;
import org.hibernate.StatelessSession;
import org.hibernate.event.spi.PostCommitInsertEventListener;
import org.hibernate.event.spi.PostInsertEvent;
import org.hibernate.persister.entity.EntityPersister;

public class TicketAddHandler implements PostCommitInsertEventListener {
    @Override
    public void onPostInsertCommitFailed(PostInsertEvent event) {

    }

    @Override
    public void onPostInsert(PostInsertEvent event) {
        if (event.getEntity()instanceof Ticket){
            updateAllowedTicketType((Ticket)event.getEntity());
        }

    }

    @Override
    public boolean requiresPostCommitHanding(EntityPersister persister) {
        return false;
    }

    private void updateAllowedTicketType(Ticket ticket){
        if (ticket.getTicketType()!=null&&ticket.getOpenids()!=null && !ticket.getOpenids().isEmpty()){
            int ticketTypeId=ticket.getTicketType().getId();
            String hql="update ticketType tt set tt.allowedTickets=tt.maxLength-(select count(t.id) from ticket t where t.ttid=:ticketTypeId) where tt.id=:ticketTypeId";
            StatelessSession session=HibernateUtil.INSTANCE.getSessionFactory().openStatelessSession();
            session.beginTransaction();
            session.createSQLQuery(hql)
                    .setParameter("ticketTypeId",ticketTypeId)
                    .executeUpdate();
            session.getTransaction().commit();
        }

    }
}
